package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * 简易的网络回显服务 请求是啥就返回啥
 */
@SuppressWarnings({"all"})
public class UdpEchoServer {
    // 准备 socket 实例
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port); // 绑定一个端口号 根据端口号区分应用程序
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器!");
        // UDP不需要建立连接，直接接收从客户端来的数据即可
        while (true){
            // 1. 读取客户端的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);
            // 解析成 String
            String request =
                    new String(requestPacket.getData(), 0, requestPacket.getLength(), "UTF-8");
            // 2. 根据请求计算响应
            String response = process(request);
            // 3. 返回响应
            // 在发送数据时 指定数据报发给谁
            DatagramPacket responsePacket =
                    new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req: %s, resp: %s\n",
                    requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }

    // 回显服务 响应和请求一样
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
